/* eslint-disable */
import {Dialog, Notify} from "vant";
import {getLodop} from '@/util/lodop/LodopFuncs.js'
import LodopModel from '@/util/lodop/LodopModel.js'

let snArr = []
let userLodopModel = null
const utilPrint = {
  /**
  * @Description：打印
   * @param type dist,transfer,snprocess，其他的有 snArrParam 参数即可
   * @param pkId 主键，比如 type = dist pkId 为配送单主键
  */
  async print(type, pkId, snArrParam) {
    await this.getPrintData(type, pkId, snArrParam)
    if(this.snArr.length < 1) return

    let printer_label_type_key = localStorage.getItem('printer_label_type_key')
    let printer_label_server_url = localStorage.getItem('printer_label_server_url')
    if(printer_label_type_key) {
      if (printer_label_type_key.toUpperCase() == 'RFID') {
        this._printRFID()
      }else if (printer_label_type_key.toUpperCase() == 'LABEL') {
        await global.utilPrint.isNeedCLodopfuncs(printer_label_server_url)
        setTimeout(() => {
          this._printLabel()
        }, 1000)
      }

    }else {
      Notify({
        type: 'warning',
        message: '未找到打印机设置，请到系统设置-->打印机设置进行设置',
        duration: 3 * 1000
      })
    }
  },

  //RFID打印机
  _printRFID(){
    let printer_label_id = localStorage.getItem('printer_label_id')
    if(!printer_label_id) {
      Notify({
        type: 'warning',
        message: '未找到打印机设置，请到系统设置-->打印机设置进行设置',
        duration: 3 * 1000
      })
      return
    }

    global.utils.loadShow(true)
    let params={
      snArr: this.snArr,
      printerId: printer_label_id
    }
    global.$ajax.post('/tool/printRFID',params).then(resp => {
      if (resp.code == 0) {
        this.$message.success(resp.msg)
      }
      global.utils.loadHide()
    })
  },


  //普通标签打印
  async _printLabel(){
    var param={
      checkUsable:true
    }
    this.userLodopModel = new window.LodopModel(param);
    if(!this.userLodopModel.lodop){
      let printer_label_server_url = localStorage.getItem('printer_label_server_url')
      Dialog.alert({
        title: '系统提示',
        message: '未发现可用的打印服务，ip='+printer_label_server_url,
      })
      return
    }


    //查询库存数据
    let wrapper = global.$newWrapper().in('sn',this.snArr )
    const params = {
      queryString: JSON.stringify(wrapper.queryConditions),
      orderString: null
    }
    global.utils.loadShow(true)
    global.$ajax.get('wm/stock/list', {params}).then(resp => {
      console.log('resp', resp)
      if (resp.code == 0  ) {
        //设置打印机属性
        console.log('localStorage.getItem(\'printer_label_print_name\')', localStorage.getItem('printer_label_print_name'))
        this.userLodopModel.printerName = localStorage.getItem('printer_label_print_name')
        let home = global.vue.$children[0].$children[0]
        home.printrows = resp.data

        setTimeout(() => {
          let printBox = $('#printBox')
          //分页
          $('.pagebreak').remove()
          let dataTableNum = $('.dataTableBox').length
          if(dataTableNum >1){
            $('.dataTableBox').after('<p class="pagebreak" style="page-break-after:always;    height: 0px;padding: 0px;margin: 0px;">&nbsp;&nbsp;&nbsp;</p>')
            $('.pagebreak:last').remove()
          }
          // this.userLodopModel.addPrintHtml(printBox.prop("outerHTML"))

          let childLength = $('.dataTableBox').length

          try {
            $('.dataTableBox').each((index, element) => {
              this.userLodopModel.addPrintHtml($(element).prop("outerHTML"))
              if (index != childLength - 1) {
                this.userLodopModel.lodop.NewPage()
              }
            })
          }catch (e) {
            console.error('e', e)
          }

          this.userLodopModel.setPrinter()
          let that = this
          this.userLodopModel.lodop.On_Return=function(TaskID,Value){
            console.log('TaskID==', TaskID)
            console.log('Value==', Value)
            setTimeout(() => {
              Notify({
                type: 'success',
                message: '打印任务已提交',
                duration: 3 * 1000
              })
              global.utils.loadHide()
            }, 1000)
          };
          this.userLodopModel.lodop.PRINT();
        }, 500)
      } else {
        global.utils.loadHide()
      }
    })
  },

  //获取打印数据
  async getPrintData(type, pkId, snArrParam ) {
    if(!type) {
      Notify({
        type: 'warning',
        message: '缺少参数【type】',
        duration: 3 * 1000
      })
      return
    }
    if(!pkId) {
      Notify({
        type: 'warning',
        message: '缺少参数【pkId】',
        duration: 3 * 1000
      })
      return
    }

    let url = '/wm/stock_process_item/list'
    let snArr = []
    let pkName = 'process_id'

    if(type == 'transfer') {
      url = '/wm/transfer_item/list'
      pkName = 'transfer_id'
    }else  if(type == 'dist') {
      url = '/wm/pick_item/list'
      pkName = 'dist_id'
    }else if(type == 'inOrder') {
      url = '/wm/stock/pageForPrint'
      pkName = 'work_order_id'
    }else if(type == 'snprocessmerge'){ //标签合并
      this.snArr = snArrParam
      return
    }else { //其他
      this.snArr = snArrParam
      return
    }

    let wrapper = global.$newWrapper().eq(pkName, pkId)
    const qString = JSON.stringify(wrapper.queryConditions)
    const params = {
      queryString: qString,
    }
    this.snArr = []
    await global.$ajax.get(url, {params}).then(response => {
      if (response.code == 0) {
        if (response.data.length > 0) {
          response.data.forEach(ob => {
            this.snArr.push(ob.sn)
          })
        } else {
          Notify({
            type: 'warning',
            message: '未找到相关可打印数据',
            duration: 3 * 1000
          })
        }
      }
    })
  },
  /**检查打印客户端依赖依赖
   */
  isNeedCLodopfuncs(printServer){
    var head = document.head || document.getElementsByTagName("head")[0] || document.documentElement;
    var oscript = document.createElement("script");

    if (!printServer) printServer = "localhost"
    oscript.src ="http://"+printServer+":8000/CLodopfuncs.js?priority=1";
    try {
      head.insertBefore( oscript,head.firstChild );
      //引用双端口(8000和18000）避免其中某个被占用：
      oscript = document.createElement("script");
      oscript.src ="http://"+printServer+":18000/CLodopfuncs.js?priority=0";
      head.insertBefore( oscript,head.firstChild );
    }catch (e) {
      console.error(e)
    }
  },

  //打开RFID扫描界面
  openRfidScan(){
    let home = global.vue.$children[0].$children[0]
    home.rfidList = []
    home.scanBegin = false
    home.scanEnd = false
    home.rfidScanMsg = '盘询结果：暂无'
    home.showRfidScan = true
  },
}

export default utilPrint
